package com.screen.screendisplay.service.impl.ne;

import com.screen.screendisplay.entity.ne.NeProdoperTimeRate;
import com.screen.screendisplay.mapper.ne.NeProdoperTimeRateMapper;
import com.screen.screendisplay.service.ne.NeProdoperTimeRateService;
import com.screen.screendisplay.vo.ne.NeTimeUtilizationRateVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 风电光电时间利用率表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class NeProdoperTimeRateServiceImpl extends ServiceImpl<NeProdoperTimeRateMapper, NeProdoperTimeRate> implements NeProdoperTimeRateService {

    @Autowired
    private NeProdoperTimeRateMapper neProdoperTimeRateMapper;

    @Override
    public List<NeTimeUtilizationRateVO> getTimeUtilizationRate(Integer year) {
        List<NeProdoperTimeRate> dataList = neProdoperTimeRateMapper.selectMonthlyUtilizationData(12);
        
        // 按年月分组，每组包含风电和光电数据
        Map<String, List<NeProdoperTimeRate>> groupedData = dataList.stream()
                .collect(Collectors.groupingBy(data -> data.getYear() + "-" + data.getMonth()));
        
        List<NeTimeUtilizationRateVO> resultList = new ArrayList<>();
        
        // 遍历分组数据，构建VO对象
        groupedData.entrySet().stream()
                .sorted((e1, e2) -> e2.getKey().compareTo(e1.getKey())) // 按时间倒序
                .limit(6) // 只取最近6个月
                .forEach(entry -> {
                    List<NeProdoperTimeRate> monthData = entry.getValue();
                    
                    NeTimeUtilizationRateVO vo = new NeTimeUtilizationRateVO();
                    
                    // 设置年份和月份（从第一条记录获取）
                    if (!monthData.isEmpty()) {
                        vo.setYear(monthData.get(0).getYear());
                        vo.setMonth(monthData.get(0).getMonth());
                    }
                    
                    // 分别设置风电和光电时间利用率
                    for (NeProdoperTimeRate data : monthData) {
                        if (data.getEnergyType() == 0) { // 风电
                            vo.setWindUtilizationRate(data.getUtilizationRate());
                        } else if (data.getEnergyType() == 1) { // 光电
                            vo.setSolarUtilizationRate(data.getUtilizationRate());
                        }
                    }
                    
                    resultList.add(vo);
                });
        
        return resultList;
    }
}
